<template>
	<div>
		<div id="flow"></div>
	</div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import LogicFlow from '@logicflow/core'
import { Control, Menu, DndPanel, SelectionSelect } from '@logicflow/extension'
import '@logicflow/core/dist/style/index.css'
import '@logicflow/extension/lib/style/index.css'
import { registerCircle, registerRect } from './registerNode'
import { message } from 'ant-design-vue'

LogicFlow.use(Control) // 控制面板
LogicFlow.use(Menu) // 右键菜单
LogicFlow.use(DndPanel) // 拖拽面板
LogicFlow.use(SelectionSelect) // 框选

export default {
	name: 'LogicFlow',
	props: {
		nodeData: {
			type: Object,
			default: () => {}
		}
	},
	emits: ['node-click', 'blank-click'],
	setup(props, { emit }) {
		// data
		const lf = ref(null)
		const config = reactive({
			stopScrollGraph: true,
			stopZoomGraph: true,
			snapline: true,
			keyboard: {
				enabled: true
			},
			height: '100%',
			grid: {
				type: 'dot',
				size: 10
			},
			textEdit: false,
			style: {
				rect: {
					// 矩形样式
					width: 80,
					height: 40,
					radius: 6,
					stroke: '#187DFF'
				},
				circle: {
					// 圆形样式
					r: 20,
					stroke: '#187DFF'
				},
				line: {
					// 直线
					stroke: '#187DFF'
				},
				polyline: {
					// 折线
					stroke: '#187DFF'
				}
			}
		})

		// methods
		const initFlow = () => {
			const lfInstance = new LogicFlow({
				...config,
				container: document.querySelector('#flow')
			})
			lf.value = lfInstance

			registerCircle(lf.value)
			registerRect(lf.value)

			lf.value.setPatternItems([
				{
					text: '选区',
					label: '选区',
					icon: '',
					callback: () => {
						lf.value.updateEditConfig({
							stopMoveGraph: true
						})
					}
				},
				{
					type: 'circle',
					text: '开始',
					label: '开始',
					icon: ''
				},
				{
					type: 'rect',
					text: '节点',
					label: '节点',
					icon: '',
					cls: 'important-node'
				},
				{
					type: 'circle',
					text: '结束',
					label: '结束',
					icon: ''
				}
			])
			lf.value.render()
			eventFlow()
		}

		const eventFlow = () => {
			// 节点点击
			lf.value.on('node:click', ({ data }) => {
				emit('node-click', data)
			})
			/* this.lf.on('edge:click', ({ data }) => {
        console.log('edge:click', data)
      }) */
			lf.value.on('connection:not-allowed', (data) => {
				message.error(data.msg)
			})
			// 画布点击
			lf.value.on('blank:click', (e) => {
				emit('blank-click', e)
			})
		}

		const uppdateNodeEdgeText = (id, val) => {
			lf.value.updateText(id, val)
		}

		const getFlowData = () => {
			return lf.value.getGraphData()
		}

		// lifecycle
		onMounted(() => {
			initFlow()
		})

		return {
			lf,
			config,

			initFlow,
			getFlowData,
			eventFlow,
			uppdateNodeEdgeText
		}
	}
}
</script>

<style lang="less" scoped>
#flow {
	height: calc(100vh - 108px);
}
</style>
